package com.example.front.serivce;

import com.example.common.dto.ListDto;
import com.example.common.dto.Pagination;
import com.example.common.exception.BusinessException;
import com.example.front.dto.LevelDto;
import com.example.front.entity.Level;
import com.example.front.mapper.LevelMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class LevelService {

    @Resource
    LevelMapper levelMapper;

    /**
     * 添加严重等级
     */
    public void createLevel(Level level) {
        List<Level> list = new ArrayList<>();
        if (!Objects.equals(levelMapper.findAll(level, new Pagination()), list)) {
            throw new BusinessException("名称已存在");
        }
        levelMapper.create(level);
    }



    /**
     * 列出严重等级列表
     */
    public ListDto<LevelDto> listLevel(Level condition, Pagination pagination) {

        List<Level> levelList = levelMapper.findAll(condition, pagination);

        List<LevelDto> listDtoList = levelList.stream().map(level -> {
            LevelDto levelDto = new LevelDto();
            BeanUtils.copyProperties(level, levelDto);
            return levelDto;
        }).collect(Collectors.toList());

        return new ListDto<>(listDtoList, pagination);
    }

    /**
     * 根据id列出严重等级列表
     */
    public Level levelById(Long id) {
       return levelMapper.findById(id);
    }

    /**
     * 根据pid列出严重等级列表
     */
    public Level levelByPid(Long id) {
        return levelMapper.findByPid(id);
    }

    /**
     * 修改严重等级信息
     */
    public void updateLevel(long id, LevelDto levelDto) {
        List<Level> list = new ArrayList<>();

        Level level = new Level();
        BeanUtils.copyProperties(levelDto, level);
        level.setTenantId(id);
//
//        if (!Objects.equals(levelMapper.findAll(level, new Pagination()), list)) {
//            throw new BusinessException("名称已存在");
//        }

        if (levelMapper.update(level) == 0) {
            throw new BusinessException("操作异常");
        }
    }

    /**
     * 删除严重等级信息
     */
    public void deleteLevel(long tenantId, Long id) {
        if(id!=1){
            throw new BusinessException("基础数据不能删除");
        }
        Level level = Level.builder().
                id(id).
                tenantId(tenantId).build();
        if (levelMapper.delete(level) == 0) {
            throw new BusinessException("删除失败");
        }
    }

}
